<template>
  <div class="app-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-row :gutter="20" class="search-row">
        <el-col :span="6">
          <el-input v-model="searchParams.group" placeholder="请输入分组" clearable @clear="handleSearch" @keyup.enter="handleSearch">
            <template #prepend>分组</template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="handleAdd">新增轮播图</el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 轮播图列表 -->
    <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="sort" label="排序" width="80" sortable />
      <el-table-column prop="group" label="分组" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="subtitle" label="副标题" show-overflow-tooltip />
      <el-table-column prop="imageUrl" label="轮播图片">
        <template #default="{ row }">
          <el-image v-if="row.imageUrl" :src="row.imageUrl" :preview-src-list="[row.imageUrl]" class="table-image" fit="contain" />
          <span v-else class="no-image">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="link" label="链接" show-overflow-tooltip>
        <template #default="{ row }">
          <el-link v-if="row.link" :href="row.link" target="_blank" type="primary">{{ row.link }}</el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" center :destroy-on-close="true" :close-on-click-modal="false" width="600px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="分组" prop="group">
          <el-input v-model="formData.group" placeholder="请输入分组" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="formData.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" placeholder="请输入排序" style="width: 100%" />
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="formData.link" placeholder="请输入链接地址（可选）" />
        </el-form-item>
        <el-form-item label="轮播图片" prop="imageUrl">
          <ImageSelector type="img" v-model:imgUrl="formData.imageUrl" :preview-src-list="[formData.imageUrl]" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { createCarousel, getCarouselList, getCarouselById, updateCarousel, deleteCarousel, batchDeleteCarousel } from "@/api/webbase";
import { useRouter } from "vue-router";
import ImageSelector from "@/components/ImageSelector/index.vue";

// 表单引用
const formRef = ref<FormInstance>();

// 路由
const router = useRouter();

// 加载状态
const tableLoading = ref(false);
const searchLoading = ref(false);
const submitLoading = ref(false);

// 弹窗状态
const dialogVisible = ref(false);
const dialogTitle = ref("");
const isEdit = ref(false);

// 表格数据
const tableData = ref([]);
const selectedIds = ref<string[]>([]);

// 搜索参数
const searchParams = reactive({
  group: ""
});

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const formData = reactive({
  _id: "",
  group: "",
  imageUrl: "",
  link: "",
  title: "",
  subtitle: "",
  sort: 0
});

// 表单验证规则
const rules: FormRules = {
  group: [{ required: true, message: "分组不能为空", trigger: "blur" }],
  imageUrl: [{ required: true, message: "图片URL不能为空", trigger: "blur" }],
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  link: [
    {
      pattern: /^https?:\/\/.+/,
      message: "请输入正确的链接格式",
      trigger: "blur"
    }
  ]
};

/**
 * 获取轮播图列表数据
 * 从接口获取轮播图列表并更新表格数据
 */
const fetchCarouselList = async () => {
  try {
    tableLoading.value = true;
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchParams
    };
    const res = await getCarouselList(params);
    if (res.data) {
      tableData.value = res.data.data || [];
      pagination.total = res.data.total || 0;
    }
  } catch (error) {
    console.error("获取轮播图列表失败:", error);
    ElMessage.error("获取轮播图列表失败");
  } finally {
    tableLoading.value = false;
  }
};

/**
 * 搜索轮播图
 * 重置分页并重新获取数据
 */
const handleSearch = async () => {
  searchLoading.value = true;
  pagination.pageNum = 1;
  await fetchCarouselList();
  searchLoading.value = false;
};

/**
 * 重置搜索条件
 * 清空搜索参数并重新获取数据
 */
const handleReset = () => {
  searchParams.group = "";
  handleSearch();
};

/**
 * 处理分页大小变化
 * 更新分页大小并重新获取数据
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  fetchCarouselList();
};

/**
 * 处理当前页变化
 * 更新当前页并重新获取数据
 */
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page;
  fetchCarouselList();
};

/**
 * 处理表格选择变化
 * 更新选中的ID列表
 */
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map((item) => item._id);
};

/**
 * 新增轮播图
 * 打开新增弹窗
 */
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增轮播图";
  resetFormData();
  dialogVisible.value = true;
};

/**
 * 编辑轮播图
 * 获取轮播图数据并打开编辑弹窗
 */
const handleEdit = async (row: any) => {
  try {
    isEdit.value = true;
    dialogTitle.value = "编辑轮播图";
    const res = await getCarouselById(row._id);
    if (res.data) {
      Object.assign(formData, res.data);
    }
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取轮播图详情失败:", error);
    ElMessage.error("获取轮播图详情失败");
  }
};

/**
 * 删除轮播图
 * 确认后删除单个轮播图
 */
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除轮播图"${row.title}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await deleteCarousel(row._id);
      ElMessage.success("删除成功");
      fetchCarouselList();
    } catch (error) {
      console.error("删除轮播图失败:", error);
      ElMessage.error("删除轮播图失败");
    }
  });
};

/**
 * 批量删除轮播图
 * 确认后批量删除选中的轮播图
 */
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}个轮播图吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await batchDeleteCarousel(selectedIds.value);
      ElMessage.success("批量删除成功");
      selectedIds.value = [];
      fetchCarouselList();
    } catch (error) {
      console.error("批量删除轮播图失败:", error);
      ElMessage.error("批量删除轮播图失败");
    }
  });
};

/**
 * 提交表单数据
 * 根据是否为编辑模式调用新增或更新接口
 */
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (isEdit.value && formData._id) {
      // 更新轮播图 - 去除_id字段
      const { _id, ...updateData } = formData;
      await updateCarousel(_id, updateData);
      ElMessage.success("轮播图更新成功");
    } else {
      // 创建轮播图，不传递_id字段
      const { _id, ...createData } = formData;
      console.log(createData, "createData");

      await createCarousel(createData);
      ElMessage.success("轮播图创建成功");
    }

    dialogVisible.value = false;
    fetchCarouselList();
  } catch (error) {
    console.error("保存轮播图失败:", error);
    ElMessage.error("保存轮播图失败");
  } finally {
    submitLoading.value = false;
  }
};

/**
 * 重置表单数据
 * 清空表单所有字段
 */
const resetFormData = () => {
  Object.assign(formData, {
    _id: "",
    group: "",
    imageUrl: "",
    link: "",
    title: "",
    subtitle: "",
    sort: 0
  });
  if (formRef.value) {
    formRef.value.resetFields();
  }
};



// 页面挂载时获取数据
onMounted(() => {
  fetchCarouselList();
});
</script>

<style scoped lang="less">
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-row {
  align-items: center;
}

.text-right {
  text-align: right;
}

.table-card {
  .table-image {
    width: 60px;
    height: 40px;
    border-radius: 4px;
  }

  .no-image {
    color: #c0c4cc;
    font-size: 12px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
